import Vue from "vue"
import VueRouter from "vue-router"
import Cookie from 'js-cookie'
Vue.use(VueRouter)

// 1 创建路由组建
// import Home from '../views/Home'
// import User from '../views/User'
import Main from '../views/Main'
// import Mall from '../views/Mall'
// import PageOne from '../views/PageOne'
// import PageTwo from '../views/PageTwo' 
import Login from '../views/Login' 

// 2. 定义一些路由
// 每个路由都需要映射到一个组件。
const routes = [
    {
        path:'/',
        // 主路由
        component:Main,
        name: "main",
        redirect:'login', //重定向
        children:[
            // {
            //     name: "home",
            //     path:'/home',
            //     component:Home
            // },
            // {
            //     name: "user",
            //     path:'/user',
            //     component:User
            // },
            // {
            //     name: "mall",
            //     path:'/mall',
            //     component:Mall
            // },
            // {
            //     name: "page1",
            //     path:'/page1',
            //     component:PageOne
            // },
            // {
            //     name: "page2",
            //     path:'/page2',
            //     component:PageTwo
            // },
        ]
    },
    {
        name: "login",
        path:'/login',
        component:Login
    }
]

// 3. 创建路由实例并传递 `routes` 配置
const router = new VueRouter({
    routes,
  })

router.beforeEach((to, from, next)=>{
    // 判断cookie是否存在
    const token = Cookie.get('token')
    if (to.name !== 'login' && !token){
        next({name:'login'})
    }else if(token && to.name === 'login'){
        next({name:'home'})
    }else{
        next()
    }
})

export default router
